<?php

class jqgridGrid extends Object{

    private $node = "";
    private $summaryrows = NULL;
    private $options = array();
    private $gridoptions = array();
    private $selection = array();
    private $arr = array();
    private $join = "";
    private $ExtraQuery = "";
    private $gridarr = "";
    private $efintegration = "";
    public function  __construct($url) {
        $this->url = $url . "/";
        $this->LoadResource('database', 'db');
        require_once 'files/jq-config.php';
    }

    public function execute($titulo, $model, $query = "", $gridarr = array()){
        
        if($query != ""){
            $_SESSION['jqgrid_query'][$model]['query'] = $query;
            $_SESSION['jqgrid_query'][$model]['garr']  = $gridarr;
        }else{
            if($query == ""     && isset($_SESSION['jqgrid_query'][$model]['query'])) $query   = $_SESSION['jqgrid_query'][$model]['query'];
            if(empty ($gridarr) && isset($_SESSION['jqgrid_query'][$model]['garr']))  $gridarr = $_SESSION['jqgrid_query'][$model]['garr'] ;
        }
        if($titulo == ""){
            $titulo = explode("/", $model);
            $titulo = ucfirst(end($titulo));
        }
        $this->gridarr = $gridarr;
        //$this->gridarr = null;
        $this->ExtraQuery = ($query == "")?NULL:"WHERE $query ";
        $this->configure($model, $titulo);
        $this->formIntegration($model);
       
        $gridarr = array_values($gridarr);
        ($this->node == "") ?
           $this->grid->renderGrid("#$this->list","#$this->pager" ,true, null, $gridarr, true, true):
           $this->grid->renderTree("#$this->list", "#$this->pager",true, null, $gridarr, true, true);
    }
    

    private function configure($model, $titulo){
        $this->LoadModel($model, 'model');
        $tabela = $this->model->getTable();
        $dados  = $this->model->getDados();
        $pkey = array();
        foreach($dados as $name => $arr){
            $nm = $name;
            if(!array_key_exists("grid", $arr)) continue;
            if(array_key_exists("pkey", $arr)) $pkey[] = $name;
            if(array_key_exists('fkey', $arr)) {
                $nm = $this->fkey($name, $arr, $tabela);
                $arr['size'] = 64;
            }
            if($nm != ""){
                if(array_key_exists("name", $arr)) $this->addOption($nm, "label", $arr['name']);
                $keys[] = $nm;
            }
            if(array_key_exists("size", $arr) && array_key_exists('type', $arr)){
                $type = $arr['type'];
                if($type == 'int' || $type == 'decimal' || $type == 'float'){
                    $sz = explode(",", $arr['size']);
                    $sz = array_shift($sz);
                    $sz = $sz * 3;
                    if($sz < 120) $this->addOption($nm, "width", $sz);
                }
            }
        }

        //seta as variaveis
        $this->pkey = implode(", ", $pkey);
        
        //inicializa o grid após saber se é treegrid ou commongrid
        $this->initgrid($tabela, $this->pkey, $keys, $titulo, $model);
    }
    
    private function addOption($key, $optionname, $optionvalue){
        $this->arr[$key][$optionname] = $optionvalue;
    }
    
    private function renderOptions(){
        foreach($this->arr as $nm => $arr){
            $this->grid->setColProperty($nm, $arr); 
        }
        $this->arr = array();
    }
    
    private function initgrid($tabela, $pkey, $keys, $titulo, $model){
        
        static $i = 0; $i++;
        $this->list  = "list$i";
        $this->pager = "pager$i";
        $path  = !($this->node != "")?"jqGrid"      :"jqTreeGrid";
        $class = !($this->node != "")?"jqGridRender":"jqTreeGrid";
        if(!function_exists("loadgridobj")){
            function loadgridobj($path, $class){
                require_once ABSPATH."php/jqCalendar.php"; 
                require_once ABSPATH."php/jqGridPdo.php";
                require_once ABSPATH."php/jqAutocomplete.php";
                $conn = new PDO(DB_DSN,DB_USER,DB_PASSWORD);
                $conn->query("SET NAMES " . CHARSET);

                require_once ABSPATH."php/$path.php";
                return new $class($conn);
            }
        }
        //instancia o grid
        $this->grid = loadgridobj($path, $class);
        
        //configurações do grid
        $ks = implode(", ", $keys);
        $this->grid->SelectCommand = "SELECT $ks FROM $tabela $this->join $this->ExtraQuery";
        $this->grid->table = $tabela;
        $this->grid->setPrimaryKeyId($pkey);  
        
        $this->grid->setColModel(null, array_values($this->gridarr));
        $this->grid->setColProperty($pkey, array("editoptions"=>array("readonly"=>true)));
        $this->renderOptions();
        
        $this->grid->dataType      = 'json';
        $this->grid->cacheCount    = false;
        $this->grid->inlineNav     = false;
        $this->grid->navigator     = true;
        $this->grid->showError     = true;
        $this->grid->toolbarfilter = true; 
        
        $this->registerOption();
        $this->grid->setGridOptions(array("altRows"   => true,"caption" => "Visualizar $titulo", "hoverrows"=> true, "multiselect" => true)); 
        $this->grid->setGridOptions(array("autowidth" => true,"height"  => 'auto')); 
        $this->grid->setGridOptions(array("rowList"   => array(10,20,50,100,200), "rowNum" => 10));
        $this->grid->setGridOptions(array('sortable'  => true, "sortorder" => "DESC", "sortname" => "$this->pkey"));
        $this->grid->setGridOptions(array("editurl"   => $this->url."action.php?model=$model","url"=> $this->url."action.php?model=$model")); 
        $this->grid->setGridOptions(array("postData" => $this->gridarr));
        
        if($this->node != ""){
            $this->grid->setTreeModel('adjacency');
            $this->grid->setTableConfig(array('id'=> $pkey, 'parent'=> $this->node));
            $this->grid->autoLoadNodes = false; 
            $this->grid->expandAll     = true;
            $this->grid->setColProperty($this->node ,array("hidden"=>true));
            //$this->grid->setColProperty($this->pkey ,array("hidden"=>true));
            //$this->grid->callGridMethod("#$this->list", 'bindKeys');
        }else{
            //Número as linhas
            $this->grid->setGridOptions(array(/*"rownumbers" => true, "rownumWidth" => 35*/));
            $this->registerOption();
        }        
        /*$this->grid->addCol(array("name"=>"Ações","formatter"=> "actions","editable"=> false,
            "sortable"=> false,"resizable"=> false,"fixed"=>true, "width"=> 50), "first");*/
$this->grid->addCol(array("name"=>"Ações","formatter"=> "js:returnMyLink","editable"=> false,
    "sortable"=> false,"resizable"=> true,"fixed"=>true, "width"=> 60), "first");
        
        if(empty ($this->gridoptions)) $this->setGridOptions(array());
        //if($this->gridoptions['edit']){
            $this->grid->setGridEvent('onSelectRow', 
            "function(rowid, selected){
                if(rowid && rowid !== lastSelection) {
                    $('#$this->list').jqGrid('restoreRow', lastSelection);
                    $('#$this->list').jqGrid('editRow', rowid, true);
                    lastSelection = rowid;
                }
             }");
        //}
        $this->grid->setJSCode(
        "jQuery('#searchtoolbar').click(function(){ 
            jQuery('#$this->list')[0].triggerToolbar(); 
            return false; 
        });"); 
        
        
        $this->grid->setNavOptions('navigator', $this->gridoptions);
        // prevent some executions when not excel export 
        $oper = jqGridUtils::GetParam("oper"); 
        if($oper == "pdf") { 
            $this->grid->setPdfOptions(array(
                "header"=>true, 
                "margin_top"=>27, 
                //"header_logo"=>"logo.gif", 
                //"header_logo_width"=>30, 
                "header_title"=> $titulo, 
                "header_string"=>"Exportação de dados do site ".SITE_NOME 
             )); 
        }
    }
    
    public function setGridOptions($arr){
        $opt = array();
        $avaible = array("add", "edit","del","view", "search", "excel","pdf", "csv", "columns");
        if(empty ($arr)) $arr = array("del", "search", "excel","pdf", "csv", "columns");
        foreach($avaible as $av){
            if(in_array($av, $arr)) $opt[$av] = true;
            else $opt[$av] = false;
        }
        $this->gridoptions = $opt;
    }
    
    private function fkey($name, &$arr, $tabela){
        $fk      = $arr['fkey'];
        $card    = $fk['cardinalidade'];
        $fkmodel = $fk['model'];
        $keys    = $fk['keys'];
        $k1      = $keys[0];
        $k2      = $keys[1];

        $this->LoadModel($fkmodel, 'fkmodel');
        $tb2 = $this->fkmodel->getTable();
        if($card == "1n"){
            if($tb2 == $tabela){
                if(!array_key_exists("treegrid", $this->options)){
                    $this->node = $name;
                    $exp = array_key_exists(1, $keys)?$keys[1]:$name;
                    $this->setOptions(array('ExpandColumn' => $exp));
                }
                return $name;
            }

            $this->AddJoin($tb2, $name, $k1);
            $this->addSelection($name, "SELECT $k1, $k2 FROM $tb2 ORDER BY $k2");
            return $k2;
        }
        elseif($card == "11"){
            if($name == "album"){
                //$this->AddJoin($tb2, $name, $k1);
            }
            $dados = $this->fkmodel->getDados();
            $this->AddJoin($tb2, $name, $k1);
            foreach($dados as $nms => $a){
                if(array_key_exists("grid", $a)){
                    $arr[$nms] = $a;
                }
            }
        }
        
    }
    
    private function addSelection($name, $query){
        $this->selection[$name] = $query;
    }
    
    private function AddJoin($tabela2, $k1src, $k2src){
        if($k1src == $k2src)$this->join .= " NATURAL JOIN $tabela2 ";
        else $this->join .= " LEFT JOIN $tabela2 ON $k1src = $k2src ";
    }
    
    private function setOptions($options){
        if(!is_array($options) || empty ($options))return;
        $this->options[] = $options;
    }
    
    private function registerOption(){
        foreach($this->options as $arr) $this->grid->setGridOptions($arr); 
        $this->options = array();
        foreach($this->selection as $name => $query){
            $this->grid->setSelect($name, $query, true, false);
            $this->grid->setAutocomplete($name,false,$query,null,true,true);
        }
        $this->selection = array();
    }
    
    private function formIntegration($model){
        if(!defined("is_admin")) {return;}
        $this->LoadResource("html", "Html");
        $url  = $this->Html->getLink($model);
        $edit = $url . "/inserir/";
        if($this->efintegration == ""){
$custom = <<<CUSTOM
        function returnMyLink(cellValue, options, rowdata) {
            var temp = "<a href='$edit" + options.rowId + "' class='ui-icon ui-icon-pencil' target='__blank'></a>";
            return temp;
        }
CUSTOM;
        }else $custom = "function returnMyLink(cellValue, options, rowdata) { $this->efintegration }";
        
        $this->grid->setJSCode($custom);
    }
    
    public function setEditFormIntegration($funct){
        $this->efintegration = $funct;
    }

}

?>
